package com.alinesno.cloud.gateway.core.filter;

import java.net.InetSocketAddress;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alinesno.cloud.gateway.core.annotation.GatewayFilter;
import com.alinesno.cloud.gateway.core.annotation.GatewayHttpResponseFilter;
import com.alinesno.cloud.gateway.core.exception.GatewayException;

/**
 * 过滤器
 * @author WeiXiaoJin
 * @since 2019年9月22日 上午12:15:30
 */
@Service
public class FilterExecutionChain extends ExecutionChain {
	
	
	/**
	 * 过滤器调用 
	 * @param insocket
	 * @param requestMsg
	 * @return
	 */
	public FilterBean doFilter(InetSocketAddress insocket, Map<String , Object> requestMsg , String gatewayType) {
		FilterBean bean = new FilterBean(true) ; 

		try {
			for(Filter f : interceptorList) {
				GatewayFilter gF = f.getClass().getAnnotation(GatewayFilter.class) ; 
				if(gF == null) {
					continue ; 
				}
				
				if(gF.skip()) { // 插件跳过
					continue ; 
				}
				f.doFilter(insocket, requestMsg , gatewayType); 
			}
		} catch (GatewayException e) {
			log.error("过滤器错误:{}" , e);
			bean.setTag(false);
		}
		
		return bean ;
	}

	/**
	 * 数据返回过滤处理
	 * @param inetSocketAddress
	 * @param returnMap
	 * @param backObj
	 * @return 
	 */
	public FilterBean doResponseFilter(InetSocketAddress inetSocketAddress, Map<String, Object> returnMap, Object backObj , String gatewayTpe) {
		FilterBean bean = new FilterBean(true) ; 
		
		try {
			for(Filter f : interceptorList) {
				GatewayHttpResponseFilter gF = f.getClass().getAnnotation(GatewayHttpResponseFilter.class) ; 
				if(gF == null) {
					continue ; 
				}
				
				if(gF.skip()) { // 插件跳过
					continue ; 
				}
				
				returnMap.put("HTTP_RESPONSE_KEY" , backObj) ; 
				f.doFilter(inetSocketAddress, returnMap , gatewayTpe); 
			}
		} catch (GatewayException e) {
			log.error("过滤器错误:{}" , e);
			bean.setTag(false);
		}
		
		return bean ;
	}


}
